export type URIParams = { [key: string]: string | number | boolean };
export class Helper {

  /** 查询字符串，对键和值进行编码 */
  public static EncodeQuery(uri_params: URIParams): string {
    return Object.keys(uri_params).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(uri_params[key])).join("&");
  }
  public static DecodeQuery(uri: string): URIParams {
    return uri.substring(uri.lastIndexOf("?") + 1).split("&").reduce((params, now) => {
      const _name = decodeURIComponent(now.substring(0, now.indexOf("="))); const _value = now.substring(now.indexOf("=") + 1); if (now && _name && _value) params[_name] = decodeURIComponent(_value); return params;
    }, {})
  }
  public static async EncodeBlob2Base64(blob: Blob): Promise<string> {
    const buf = await blob.arrayBuffer();
    return ":" + blob.type + ";," + btoa(String.fromCharCode(... new Uint8Array(buf)));
  }
  public static DecodeBase642Blob(base64: string): Blob {
    const hasPrefix = base64.includes(',');
    const dataPart = hasPrefix ? base64.slice(hasPrefix ? base64.indexOf(',') + 1 : 0) : base64;
    const extractedType = hasPrefix ? base64.slice(0, hasPrefix ? base64.indexOf(',') : 0).match(/:(.*?);/)?.[1] : null;
    const finalType = extractedType || 'application/octet-stream';
    const binaryString = atob(dataPart); const chunkSize = 1024 * 64;
    const chunks = [];
    for (let i = 0; i < binaryString.length; i += chunkSize) {
      const chunk = binaryString.slice(i, i + chunkSize);
      const byteNumbers = new Uint8Array(chunk.length);
      for (let j = 0; j < chunk.length; j++) byteNumbers[j] = chunk.charCodeAt(j);
      chunks.push(byteNumbers);
    }

    return new Blob(chunks, { type: finalType });
  }

}